/**
 * This class handles network traffic
 * @author cathbar
 */
package com.dylankenny.flikrreader.model.parse;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.os.Environment;

public class NetworkManager {

	public static final String PATH = Environment.getExternalStorageDirectory().getPath() + "/flickrReader/";

	/**
	 * Download an image into the external storage directory.
	 * 
	 * @author cathbar
	 * @param inputUrl
	 * @param fileName
	 */
	public static void DownloadImageToFS(String inputUrl, String fileName) {
		try {

			File dir = new File(PATH);
			dir.mkdirs();

			URL url = new URL(inputUrl);
			File file = new File(fileName);

			URLConnection ucon;

			ucon = url.openConnection();

			InputStream is = ucon.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);

			ByteArrayBuffer baf = new ByteArrayBuffer(50);
			int current = 0;
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}

			FileOutputStream fos = new FileOutputStream(file);
			fos.write(baf.toByteArray());
			fos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * This method will download the url into a String and return it. This is
	 * not a very scalable idea, considering how potentially big the String
	 * could be. I would recommend downloading the file to the filesystem, then
	 * read/interpret it later on, giving you more freedom in how to handle
	 * large inputs.
	 * 
	 * @author cathbar
	 * @param inputUrl
	 * @param fileName
	 * @return
	 */
	public static String DownloadFromUrlToString(String inputUrl) {
		String result = "";
		try {

			URL url = new URL(inputUrl);

			URLConnection ucon;

			ucon = url.openConnection();

			InputStream is = ucon.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);

			ByteArrayBuffer baf = new ByteArrayBuffer(50);
			int current = 0;
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}

			result += new String(baf.toByteArray());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
}